<template>
  <div class="review-management">
    <h2 class="page-title">评价管理</h2>
    
    <!-- 评价统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-content">
            <div class="stat-number">{{ statistics.totalReviews || 0 }}</div>
            <div class="stat-title">总评价数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-content">
            <div class="stat-number">{{ statistics.avgRating ? statistics.avgRating.toFixed(1) : '0.0' }}</div>
            <div class="stat-title">平均评分</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-content">
            <div class="stat-number">{{ statistics.positiveRate ? (statistics.positiveRate * 100).toFixed(0) : 0 }}%</div>
            <div class="stat-title">好评率</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="card-content">
            <div class="stat-number">{{ statistics.replyRate ? (statistics.replyRate * 100).toFixed(0) : 0 }}%</div>
            <div class="stat-title">回复率</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="评分">
          <el-select v-model="queryParams.rating" placeholder="全部评分" clearable>
            <el-option label="全部评分" value=""></el-option>
            <el-option label="5星" :value="5"></el-option>
            <el-option label="4星" :value="4"></el-option>
            <el-option label="3星" :value="3"></el-option>
            <el-option label="2星" :value="2"></el-option>
            <el-option label="1星" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回复状态">
          <el-select v-model="queryParams.replied" placeholder="全部状态" clearable>
            <el-option label="全部状态" value=""></el-option>
            <el-option label="已回复" :value="true"></el-option>
            <el-option label="未回复" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 评价列表 -->
    <el-card class="review-list-card" v-loading="loading">
      <div v-if="reviewList.length === 0" class="empty-data">
        <i class="el-icon-chat-dot-square empty-icon"></i>
        <p>暂无评价数据</p>
      </div>
      
      <div v-else class="review-list">
        <div v-for="review in reviewList" :key="review.id" class="review-item">
          <div class="review-header">
            <div class="user-info">
              <img :src="review.avatar || ''" class="user-avatar" alt="用户头像">
              <span class="user-name">{{ review.realName }}</span>
            </div>
            <div class="review-rating">
              <el-rate v-model="review.rating" disabled show-score text-color="#ff9900"></el-rate>
              <span class="review-time">{{ review.createTime }}</span>
            </div>
          </div>
          
          <div class="review-content">
            <div class="review-text">{{ review.content }}</div>
            
            <!-- 评价图片 -->
            <div v-if="review.images && review.images.length > 0" class="review-images">
              <div 
                v-for="(image, index) in review.images" 
                :key="index" 
                class="review-image"
                @click="showImagePreview(image)">
                <img :src="image" alt="评价图片">
              </div>
            </div>
            
            <!-- 订单信息 -->
            <div class="order-info">
              <span>订单编号: {{ review.orderNo }}</span>
              <span>评价时间: {{ review.createTime }}</span>
            </div>
          </div>
          
          <!-- 商家回复 -->
          <div v-if="review.reply" class="merchant-reply">
            <div class="reply-header">
              <i class="el-icon-s-custom"></i> 商家回复
              <span class="reply-time">{{ review.replyTime }}</span>
            </div>
            <div class="reply-content">{{ review.reply }}</div>
          </div>
          
          <!-- 回复操作 -->
          <div class="review-actions">
            <el-button 
              v-if="!review.reply" 
              type="primary" 
              size="small" 
              @click="openReplyDialog(review)">回复</el-button>
            <el-button 
              v-else
              type="info" 
              size="small" 
              @click="openReplyDialog(review)">修改回复</el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="reviewList.length > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 回复对话框 -->
    <el-dialog
      :title="currentReview.replyContent ? '修改回复' : '回复评价'"
      :visible.sync="replyDialogVisible"
      width="600px">
      <div v-if="currentReview" class="reply-dialog-content">
        <div class="review-detail">
          <div class="user-review">
            <div class="review-header">
              <span class="user-name">{{ currentReview.realName }}</span>
              <el-rate v-model="currentReview.rating" disabled show-score text-color="#ff9900"></el-rate>
            </div>
            <div class="review-text">{{ currentReview.content }}</div>
            <div class="review-time">{{ currentReview.createTime }}</div>
          </div>
        </div>
        
        <el-form :model="replyForm" :rules="replyRules" ref="replyForm">
          <el-form-item prop="content" :rules="[{ required: true, message: '请输入回复内容', trigger: 'blur' }]">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容..."
              v-model="replyForm.content">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="replyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReply">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewVisible" title="图片预览" width="50%">
      <img :src="previewImage" alt="预览图片" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getReviewStatistics, getMerchantReviews } from '@/api/review'

export default {
  name: 'ReviewManagement',
  data() {
    return {
      // 商家ID
      merchantId: null,
      
      // 评价统计
      statistics: {
        totalReviews: 0,
        avgRating: 0,
        positiveRate: 0,
        replyRate: 0
      },
      
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        merchantId: null,
        rating: '',
        replied: '',
        startTime: '',
        endTime: ''
      },
      
      // 日期范围
      dateRange: [],
      
      // 评价列表
      reviewList: [],
      
      // 总记录数
      total: 0,
      
      // 加载状态
      loading: false,
      
      // 当前回复的评价
      currentReview: {},
      
      // 回复表单
      replyForm: {
        reviewId: null,
        content: ''
      },
      
      // 回复表单校验规则
      replyRules: {
        content: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { max: 500, message: '回复内容不能超过500个字符', trigger: 'blur' }
        ]
      },
      
      // 回复对话框可见性
      replyDialogVisible: false,
      
      // 图片预览
      previewVisible: false,
      previewImage: ''
    }
  },
  created() {
    this.getMerchantId()
  },
  methods: {
    // 获取商家ID
    getMerchantId() {
      const userId = this.$store.state.user.id
      axios.get(`/api/merchants/user/${userId}`)
        .then(response => {
          if (response.code === 200) {
            this.merchantId = response.data.id
            this.queryParams.merchantId = response.data.id
            
            // 获取评价统计和列表
            this.getReviewStatistics()
            this.fetchReviewList()
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 获取评价统计
    getReviewStatistics() {
      getReviewStatistics(this.merchantId)
        .then(response => {
          if (response.code === 200) {
            this.statistics = response.data
          }
        })
        .catch(error => {
          console.error('获取评价统计失败', error)
        })
    },
    
    // 获取评价列表
    fetchReviewList() {
      this.loading = true
      
      // 构建查询参数
      const params = { ...this.queryParams }
      
      getMerchantReviews(this.merchantId, params)
        .then(response => {
          if (response.code === 200) {
            this.reviewList = response.data
            this.total = response.total
          } else {
            this.$message.error(response.message || '获取评价列表失败')
          }
          this.loading = false
        })
        .catch(error => {
          console.error('获取评价列表失败', error)
          this.$message.error('获取评价列表失败')
          this.loading = false
        })
    },
    
    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startTime = val[0]
        this.queryParams.endTime = val[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.page = 1
      this.fetchReviewList()
    },
    
    // 重置查询
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        page: 1,
        size: 10,
        merchantId: this.merchantId,
        rating: '',
        replied: '',
        startTime: '',
        endTime: ''
      }
      this.fetchReviewList()
    },
    
    // 处理每页大小变化
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchReviewList()
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.fetchReviewList()
    },
    
    // 打开回复对话框
    openReplyDialog(review) {
      this.currentReview = review
      this.replyForm = {
        reviewId: review.id,
        content: review.replyContent || ''
      }
      this.replyDialogVisible = true
      
      // 在下一个事件循环重置表单验证
      this.$nextTick(() => {
        this.$refs.replyForm && this.$refs.replyForm.clearValidate()
      })
    },
    
    // 提交回复
    submitReply() {
      this.$refs.replyForm.validate((valid) => {
        if (valid) {
          const isUpdate = !!this.currentReview.replyContent
          const apiUrl = isUpdate 
            ? `/api/reviews/${this.replyForm.reviewId}/reply/update`
            : `/api/reviews/${this.replyForm.reviewId}/reply`
          
          axios.post(apiUrl, {
            merchantId: this.merchantId,
            content: this.replyForm.content
          })
            .then(response => {
              if (response.code === 200) {
                this.$message.success(isUpdate ? '修改回复成功' : '回复成功')
                this.replyDialogVisible = false
                this.fetchReviewList()
                this.getReviewStatistics()
              } else {
                this.$message.error(response.message || '操作失败')
              }
            })
            .catch(error => {
              console.error('回复评价失败', error)
              this.$message.error('操作失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 显示图片预览
    showImagePreview(url) {
      this.previewImage = url
      this.previewVisible = true
    }
  }
}
</script>

<style scoped>
.review-management {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-content {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #409EFF;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.filter-card {
  margin-bottom: 20px;
}

.review-list-card {
  margin-bottom: 20px;
  min-height: 400px;
}

.empty-data {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #909399;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.review-list {
  margin-bottom: 20px;
}

.review-item {
  border-bottom: 1px solid #EBEEF5;
  padding: 20px 0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.user-name {
  font-weight: bold;
  color: #303133;
}

.review-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.review-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.review-content {
  margin-bottom: 15px;
}

.review-text {
  margin-bottom: 10px;
  line-height: 1.5;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.review-image {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.review-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.order-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.merchant-reply {
  background-color: #F5F7FA;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  font-weight: bold;
  color: #303133;
}

.reply-header i {
  margin-right: 5px;
  color: #409EFF;
}

.reply-time {
  margin-left: auto;
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.reply-content {
  color: #606266;
  line-height: 1.5;
}

.review-actions {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.reply-dialog-content .review-detail {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.reply-dialog-content .user-review {
  padding: 10px;
  background-color: #F5F7FA;
  border-radius: 4px;
}

.reply-dialog-content .review-text {
  margin: 10px 0;
  color: #606266;
  line-height: 1.5;
}

.reply-dialog-content .review-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
}
</style> 